﻿/*
Copyright (c) 2011 <a href="http://www.gutgames.com">James Craig</a>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

#region Usings
using System;
using System.Collections.Generic;
using System.Reflection;
using ObjectCartographer.Interfaces;
using Utilities.DataTypes.Patterns.BaseClasses;
#endregion

namespace ObjectCartographer
{
    /// <summary>
    /// Handles all setup/creation of mappings and is the interface
    /// that all requests go through
    /// </summary>
    public class Manager : Singleton<Manager>
    {
        #region Constructor

        /// <summary>
        /// Constructor
        /// </summary>
        protected Manager()
            : base()
        {
            Mappings = new List<IMapping>();
        }

        #endregion

        #region Public Functions

        /// <summary>
        /// Sets up the mappings
        /// </summary>
        /// <param name="MappingAssemblies">List of assemblies to look in for mappings</param>
        public void Setup(List<Assembly> MappingAssemblies)
        {
            Setup(MappingAssemblies, null);
        }

        /// <summary>
        /// Sets up the mappings
        /// </summary>
        /// <param name="MappingAssemblies">List of assemblies to look in for mappings</param>
        /// <param name="FactoryAssembly">Assembly which holds any type factories (only used
        /// when using FactoryMapping)</param>
        public void Setup(List<Assembly> MappingAssemblies, Assembly FactoryAssembly)
        {
            foreach (Assembly Assembly in MappingAssemblies)
            {
                Setup(Assembly, FactoryAssembly);
            }
        }

        /// <summary>
        /// Sets up the mappings
        /// </summary>
        /// <param name="Assembly">Assembly to look in for mappings</param>
        public void Setup(Assembly Assembly)
        {
            Setup(Assembly, null);
        }

        /// <summary>
        /// Sets up the mappings
        /// </summary>
        /// <param name="Assembly">Assembly to look in for mappings</param>
        /// <param name="FactoryAssembly">Assembly which holds any type factories 
        /// (only used when using FactoryMapping)</param>
        public void Setup(Assembly Assembly, Assembly FactoryAssembly)
        {
            if (FactoryAssembly != null)
            {
                List<Type> FactoryTypes = Utilities.Reflection.Reflection.GetTypes(FactoryAssembly, "ITypeMapping");
                if (FactoryTypes.Count > 0)
                {
                    Type FactoryMappingType = FactoryTypes[0];
                    TypeMapping = (ITypeMapping)FactoryMappingType.Assembly.CreateInstance(FactoryMappingType.FullName);
                }
            }
            List<Type> Types = Utilities.Reflection.Reflection.GetTypes(Assembly, "IMapping");
            foreach (Type Type in Types)
            {
                Mappings.Add((IMapping)Assembly.CreateInstance(Type.FullName));
            }
        }

        /// <summary>
        /// Copies info from the source object to the destination object
        /// </summary>
        /// <param name="Source">Source object</param>
        /// <param name="Destination">Destination object</param>
        public void Sync(object Source, object Destination)
        {
            if (Source == null || Destination == null)
                return;
            Type SourceType=Source.GetType();
            Type DestinationType=Destination.GetType();
            Sync(Source, Destination, SourceType, DestinationType);
        }

        /// <summary>
        /// Creates a destination object (or list of objects) containing the source object's info
        /// </summary>
        /// <param name="Source">Source object</param>
        /// <returns>Destination object</returns>
        public object Create(object Source)
        {
            if (Source == null)
                return null;
            Type SourceType = Source.GetType();
            return Create(Source, SourceType);
        }

        #endregion

        #region Private Functions

        /// <summary>
        /// Creates a destination object (or list of objects) containing the source object's info
        /// </summary>
        /// <param name="Source">Source object</param>
        /// <param name="SourceType">Type of the source object</param>
        /// <returns>Destination object</returns>
        private object Create(object Source, Type SourceType)
        {
            if (Source == null || SourceType == null)
                return null;
            for (int x = 0; x < Mappings.Count; ++x)
            {
                if (Mappings[x].SourceType == SourceType || Mappings[x].DestinationType == SourceType)
                {
                    return Mappings[x].Create(Source);
                }
            }
            return Create(Source, SourceType.BaseType);
        }

        /// <summary>
        /// Copies info from the source object to the destination object
        /// </summary>
        /// <param name="Source">Source object</param>
        /// <param name="Destination">Destination object</param>
        /// <param name="SourceType">Source type</param>
        /// <param name="DestinationType">Destination type</param>
        private bool Sync(object Source, object Destination, Type SourceType, Type DestinationType)
        {
            if (Source == null || Destination == null || SourceType == null || DestinationType == null)
                return false;
            for (int x = 0; x < Mappings.Count; ++x)
            {
                if ((Mappings[x].SourceType == SourceType && Mappings[x].DestinationType == DestinationType)
                    || (Mappings[x].DestinationType == SourceType && Mappings[x].SourceType == DestinationType))
                {
                    Mappings[x].Sync(Source, Destination);
                    return true;
                }
            }
            if (Sync(Source, Destination, SourceType.BaseType, DestinationType.BaseType))
                return true;
            if (Sync(Source, Destination, SourceType.BaseType, DestinationType))
                return true;
            if (Sync(Source, Destination, SourceType, DestinationType.BaseType))
                return true;
            return false;
        }

        #endregion

        #region Internal Functions

        /// <summary>
        /// Number of objects the mapping expects
        /// </summary>
        /// <param name="SourceType">The source type</param>
        /// <returns>The number of objects the mapping expects</returns>
        internal int NumberObjectsExpected(Type SourceType, Type DestinationType)
        {
            if (SourceType == null || DestinationType == null)
                return 0;
            for (int x = 0; x < Mappings.Count; ++x)
            {
                if ((Mappings[x].SourceType == SourceType && Mappings[x].DestinationType == DestinationType)
                    || (Mappings[x].DestinationType == SourceType && Mappings[x].SourceType == DestinationType))
                {
                    return Mappings[x].NumberObjectsExpected();
                }
            }
            int Value=NumberObjectsExpected(SourceType.BaseType, DestinationType.BaseType);
            if (Value>0)
                return Value;
            Value = NumberObjectsExpected(SourceType.BaseType, DestinationType);
            if (Value > 0)
                return Value;
            Value = NumberObjectsExpected(SourceType, DestinationType.BaseType);
            if (Value > 0)
                return Value;
            return 0;
        }

        #endregion

        #region Private Variables

        private List<IMapping> Mappings { get; set; }

        #endregion

        #region Public Variables

        public ITypeMapping TypeMapping { get; set; }

        #endregion
    }
}
